from flask import render_template, current_app, session, g, abort, request, json, jsonify

from info import db
from info.constants import CLICK_RANK_MAX_NEWS
from info.models import News, User, Comment, CommentLike
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import news_blu

@news_blu.route('/<int:news_id>')
@user_login_data
def news_detail(news_id):

    # user_id = session.get('user_id')
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.log.error(e)
    user = g.user
    # 查询新闻数据
    news_detail = None
    try:
        news_detail = News.query.get(news_id)
    except Exception as e:
        current_app.log.error(e)
    if not news_detail:
        abort(404)
    # 更新点击次数
    news_detail.clicks += 1

    news_list = None
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.log.error(e)
    news_list_li = []
    for news in news_list:
        news_list_li.append(news.to_basic_dict())

    # 用户是否收藏新闻
    is_collected = False
    is_followed = False
    news_collecteds = None
    if user:
        if news_detail in user.collection_news:
            is_collected = True
        if news_detail.user.followers.filter(User.id == user.id).count() > 0:
            is_followed = True

    # 查询评论数据
    comments = None

    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.log.error(e)

    comment_like_ids = []
    if user:
        try:
            comment_ids = [comment.id for comment in comments]
            comment_likes = CommentLike.query.filter(CommentLike.comment_id.in_(comment_ids),CommentLike.user_id == user.id).all()
            comment_like_ids = [comment_like.comment_id for comment_like in comment_likes]
        except Exception as e:
            current_app.log.error(e)


    comment_dict_li = []
    for comment in comments:
        # is_liked = False
        comment_dict = comment.to_dict()
        # print(comment)
        comment_dict['is_liked'] = False
        if comment.id in comment_like_ids:
            comment_dict['is_liked'] = True
        comment_dict_li.append(comment_dict)
        # if user:
        #     comment_like = CommentLike.query.filter(CommentLike.comment_id == comment.get('id'),CommentLike.user_id == user.id).first()
        #     if comment_like:
        #         comment['is_liked'] = True
        # print(is_liked)

    # is_followed = False
    # # if 当前新闻有作者 并且 登录用户关注过该作者
    # if news_detail.user and user:
    # #     user是否关注过作者
    #     if news_detail.user in user.followed:
    #         is_followed = True

    data = {
        "user":user.to_dict() if user else None,
        "news":news_detail.to_dict(),
        "news_list_li":news_list_li,
        "is_collected":is_collected,
        "comment_dict_li":comment_dict_li,
        "is_followed":is_followed
    }
    # print(data['is_liked'])
    return render_template('news/detail.html',data=data)

@news_blu.route('/news_collected',methods=['POST'])
@user_login_data
def news_collected():
    user = g.user
    if not user:
        return jsonify(errno=RET.USERERR,errmsg='用户未登录')
    # 1、获取参数
    news_id = request.json.get('news_id')
    action = request.json.get('action')
    # 2、校验参数
    if not all([news_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.log.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    if action not in ['collected','cancel_collected']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 3、查询新闻，并判断新闻是否存在
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.log.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询错误')

    if not news:
        return jsonify(errno=RET.NODATA, errmsg='news不存在')

    # 4、取消收藏
    if action == 'cancel_collected':
        if news in user.collection_news:
            user.collection_news.remove(news)
    else:
        if news not in user.collection_news:
            user.collection_news.append(news)
    return jsonify(errno=RET.OK,errmsg='操作成功')

@news_blu.route('/news_comment',methods=['POST'])
@user_login_data
def news_comment():
    user = g.user
    if not user:
        return jsonify(errno=RET.USERERR,errmsg='用户未登录')

    # 1、获取参数
    comment_content = request.json.get('comment')
    news_id = request.json.get('news_id')
    parent_id = request.json.get('parent_id')

    # 2、校验参数
    if not all([comment_content,news_id]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        news_id = int(news_id)
        if parent_id:
            parent_id = int(parent_id)
    except Exception as e:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 3、查询news是否存在
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        # db.sesson.rollback()
        return jsonify(errno=RET.DBERR, errmsg='数据查询错误')

    if not news:
        return jsonify(errno=RET.NODATA, errmsg='news不存在')

    # 4、添加评论
    comment = Comment()
    comment.user_id = user.id
    comment.news_id = news_id
    comment.content = comment_content
    if parent_id:
        comment.parent_id = parent_id
    db.session.add(comment)
    db.session.commit()
    # print(comment)
    return jsonify(errno=RET.OK,errmsg='ok',data=comment.to_dict())

@news_blu.route('/comment_like',methods=['POST'])
@user_login_data
def comment_likes():
    user = g.user
    if not user:
        return jsonify(errno=RET.USERERR, errmsg='用户未登录')

    comment_id = request.json.get('comment_id')
    # news_id = request.json.get('news_id')
    action = request.json.get('action')

    if not([comment_id,action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    if action not in ['add','remove']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        comment_id = int(comment_id)
        # news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    comment = None
    try:
        comment = Comment.query.filter(Comment.id == comment_id).first()
    except Exception as e:
        current_app.logger.error(e)
        # db.sesson.rollback()
        return jsonify(errno=RET.DBERR, errmsg='数据查询错误')

    if not comment:
        return jsonify(errno=RET.NODATA, errmsg='comment不存在')

    # is_like = False
    # comment_like = None
    # try:
    #     comment_like = CommentLike.query.filter(CommentLike.user_id == user.id)
    # except Exception as e:
    #     current_app.logger.error(e)
    #     # db.sesson.rollback()
    #     return jsonify(errno=RET.DBERR, errmsg='数据查询错误')
    # if comment_like:
    #     is_like = True

    if action == 'add':
        comment_like = CommentLike.query.filter(CommentLike.user_id == user.id, CommentLike.comment_id == comment_id).first()

        if not comment_like:
            print(action)
            comment_like = CommentLike()
            comment_like.comment_id = comment_id
            comment_like.user_id = user.id
            comment.like_count +=1
            # print(comment_like)
            db.session.add(comment_like)
    else:
        comment_like = CommentLike.query.filter(CommentLike.user_id == user.id,CommentLike.comment_id == comment_id).first()
        if comment_like:
            db.session.delete(comment_like)
            comment.like_count -= 1
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据操作错误')

    return jsonify(errno=RET.OK, errmsg='操作成功')


@news_blu.route('/user_followed',methods=['POST'])
@user_login_data
def user_followed():
    user = g.user
    if not user:
        return jsonify(errno=RET.USERERR,errmsg='未登录')

    user_id = request.json.get('user_id')
    action = request.json.get('action')

    if not all([user_id,action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    if action not in ('follow','unfollow'):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    if int(user_id) == int(user.id):
        return jsonify(errno=RET.PARAMERR,errmsg='不能自己关注自己')

    try:
        other = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询错误')

    if not other:
        return jsonify(errno=RET.NODATA, errmsg='未查到数据')

    if action == 'follow':
        if other not in user.followed:
            # 当前用户的关注列表添加一个值
            user.followed.append(other)
        else:
            return jsonify(errno=RET.DATAEXIST, errmsg='当前已被关注')
    else:
        if other in user.followed:
            user.followed.remove(other)
        else:
            return jsonify(errno=RET.DATAEXIST, errmsg='当前未被关注')
    return jsonify(errno=RET.OK,errmsg='成功')



